package com.example.smartcity.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.smartcity.R
import com.example.smartcity.http.ProductCategory

/**
 * @Author: Tailyou
 * @CreateDate: 2021/10/7 19:11
 * @Email: tailyou@163.com
 * @Description: RecycleView数据适配器（点菜-左侧menu）
 */
class ProductCategoryAdapter(
    private var data: List<ProductCategory>,
    var listener: OnItemClickListener
) :
    RecyclerView.Adapter<ProductCategoryAdapter.MViewHolder>() {

    companion object {
        private var curPosition = 0
        private fun getPosition(): Int {
            return curPosition
        }

        fun setPosition(position: Int) {
            curPosition = position
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MViewHolder {
        var view =
            LayoutInflater.from(parent.context).inflate(R.layout.layout_item_product_category, null)
        return MViewHolder(view)
    }

    override fun onBindViewHolder(holder: MViewHolder, position: Int) {
        holder.name.text = data[position].name
        holder.itemView.setOnClickListener {
            listener.onClick(position)
            notifyDataSetChanged();
        }
        holder.name.setBackgroundColor(
            if (position == getPosition()) Color.WHITE
            else Color.parseColor("#fafafa")
        )
    }

    override fun getItemCount(): Int {
        return data.size
    }

    class MViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var name: TextView = itemView.findViewById(R.id.tvName)
    }

    interface OnItemClickListener {
        fun onClick(position: Int)
    }

}